package oj_leetcode;

import java.util.HashSet;
import java.util.Set;

public class IsValidSudoku {
    public boolean isValidSudoku(char[][] board) {
        Set<Character>[] rowSets = new HashSet[9];
        Set<Character>[] columnSets = new HashSet[9];
        Set<Character>[] threeSets = new HashSet[9];
        for (int i = 0;i<9;i++){
            rowSets[i] = new HashSet<>();
            columnSets[i] = new HashSet<>();
            threeSets[i] = new HashSet<>();
        }
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                // 锁定3*3的块
                for (int r = 0; r < 3; r++) {
                    for (int c = 0; c < 3; c++) {
                        // 锁定块中的数
                        int rowSetIndex = i * 3 + r;
                        int columnSetIndex = j * 3 + c;
                        int threeSetIndex = i * 3 + j;
                        // 判断是否为.
                        if (board[rowSetIndex][columnSetIndex] == '.') {
                            continue;
                        }

                        // 判断有没有该行
                        Set<Character> rowSet = rowSets[rowSetIndex];
                        // 判断该行中是否存在该数
                        if (rowSet.contains(board[rowSetIndex][columnSetIndex])) {
                            return false;
                        } else {
                            rowSet.add(board[rowSetIndex][columnSetIndex]);
                        }

                        // 判断有没有该列
                        Set<Character> columnSet = columnSets[rowSetIndex];
                        // 判断该行中是否存在该数
                        if (columnSet.contains(board[rowSetIndex][columnSetIndex])) {
                            return false;
                        } else {
                            columnSet.add(board[rowSetIndex][columnSetIndex]);
                        }

                        // 判断3*3
                        Set<Character> threeSet = threeSets[rowSetIndex];
                        // 判断3*3有没有该数
                        if (threeSet.contains(board[rowSetIndex][columnSetIndex])) {
                            return false;
                        } else {
                            threeSet.add(board[rowSetIndex][columnSetIndex]);
                        }
                    }
                }
            }
        }
        return true;
    }
}
